package ar.utn.jess.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.google.gson.Gson;

import ar.utn.jess.common.AbstractEntity;
import ar.utn.jess.common.EditorData;
import ar.utn.jess.common.EntitySelector;
import ar.utn.jess.common.SelectorData;
import ar.utn.jess.common.Util;
import ar.utn.jess.domain.AutoActivo;
import ar.utn.jess.domain.Central;
import ar.utn.jess.domain.Chofer;
import ar.utn.jess.domain.Viaje;
import ar.utn.jess.domain.enums.EstadoChofer;
import ar.utn.jess.exception.JSSException;

public class AdministracionServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;
	private static Logger log = Logger.getLogger(AdministracionServlet.class);

	@Override
	protected void serve(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

		String action = req.getParameter("action");
		
		if(action==null) {
			
			
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/WEB-INF/pages/administracion.jsp");		
			rd.forward(req, resp);
		}
		else if(action.equals("getForGrid")) {
			getForGrid(req, resp);
		}
		else if(action.equals("autosActivosGrid")) {
			autosActivosGrid(req, resp);
		}
		else if(action.equals("cancelarViaje")) {
			cancelarViaje(req, resp);
		}
	}

	
	@SuppressWarnings("unchecked")
	protected EditorData buildEditorData(HttpServletRequest req) {
		EditorData editorData = new EditorData();
		
		Enumeration<String> en = req.getParameterNames();
		while(en.hasMoreElements()) {
			String name = en.nextElement();
			editorData.addAttribute(name, req.getParameter(name));
		}
		
		return editorData;
	}
	
	protected void getForGrid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String entityName = req.getParameter("entity");		
		
		try {
			final AbstractEntity entity = Util.createAbstractEntity(entityName);
			
			String json = ServletUtils.getJsonForJQGrid(req, entity, new EntitySelector() {
				@SuppressWarnings({ "unchecked", "static-access" })
				public List<HashMap<String, Object>> getRows(Class clazz, SelectorData selectorData) {
					return entity.findForSelector(clazz, selectorData);
				}
				
				@SuppressWarnings({ "unchecked", "static-access" })
				@Override
				public Integer getTotalRows(Class clazz, SelectorData selectorData) {
					return entity.getCountForSelector(clazz, selectorData);
				}
			});
											
			resp.setContentType("application/json;charset=utf-8");
			resp.getWriter().write(json);
		}
		catch(Exception e) {
			throw new JSSException(e);
		}						
	}
	
	protected void autosActivosGrid(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		try {
			final AbstractEntity entity = Util.createAbstractEntity("autoActivo");

			log.info("Consulta datos de administracion");
			
			String json = ServletUtils.getJsonForJQGrid(req, entity, new EntitySelector() {
				@SuppressWarnings("rawtypes")
				public List<HashMap<String, Object>> getRows(Class clazz, SelectorData selectorData) {
					
					List<HashMap<String, Object>> result = new ArrayList<HashMap<String,Object>>();
					
					for(AutoActivo auto : Central.getAutosActivos()) {
						
						HashMap<String, Object> autoRow = new LinkedHashMap<String, Object>();
						
						Chofer chofer = Chofer.findById(Chofer.class, auto.getChofer().getId());
						
						autoRow.put("id", auto.getChofer().getId());
						autoRow.put("chofer", auto.getChofer().getNombre() + " " +auto.getChofer().getApellido());
						autoRow.put("lat", auto.getUbicacion().getLatitud());
						autoRow.put("longi", auto.getUbicacion().getLongitud());
						
						String estado="";
						if(auto.getViaje()!=null) {
							if(EstadoChofer.DESLOGUEADO.equals(chofer.getEstadoChofer()))
								estado = "DESLOGUEADO";
							else
								estado = auto.getViaje().getEstado().name();
						}
						else {
							if(EstadoChofer.OCUPADO.equals(chofer.getEstadoChofer()))
								estado = "SIN VIAJE - OCUPADO";
							else if(EstadoChofer.LIBRE.equals(chofer.getEstadoChofer()))
								estado = "SIN VIAJE - LIBRE";
							else {
								estado = "DESLOGUEADO";
							}
						}
						
						autoRow.put("estado", estado);
						
//						System.out.println("ROW: "+autoRow);
						
						result.add(autoRow);
					}
					
					return result;
				}
				
				@SuppressWarnings("rawtypes")
				@Override
				public Integer getTotalRows(Class clazz, SelectorData selectorData) {
					return Central.getAutosActivos().size();
				}
			});
											
			resp.setContentType("application/json;charset=utf-8");
			resp.getWriter().write(json);
		}
		catch(Exception e) {
			e.printStackTrace();
			throw new JSSException(e);
		}						
	}
	
	protected void cancelarViaje(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		Gson gson = new Gson();
		
		Viaje viaje = Viaje.findById(Viaje.class, Integer.parseInt(req.getParameter("idviaje")));
		
		String rta = Central.cancelarViaje(viaje);
		
		viaje.update();
		
		resp.setContentType("application/json;charset=utf-8");
		resp.getWriter().write(gson.toJson(rta));
	}
}
